const express = require('express');
const r = express.Router();
const pool = require('../pool.js');
// 测试
r.get('/cs',(req,res)=>{
	res.send('cart服务器成功开启')
});

//  添加购物车
r.post("/v1/cartAdd",(req,res)=>{
	var obj = req.body;
	sql = 'insert into xz_shoppingcart_item set ? where uid=?'
	pool.query(sql,[obj,obj.uid],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});

//  购物车列表分页
r.get("/v1/cartList/:page&:count",(req,res)=>{
	var $page = req.params.page;
	var $count = req.params.count;
	$page = parseInt(($page));
	$count = parseInt(($count));
	
	sql = "select * from xz_shoppingcart_item limit ?,?"
	pool.query(sql,[$page,$count],(err,result)=>{
		if(err) throw err;
		if(result.length>0){
			res.send(result);
		}else{
			res.send("0");
		}
	});
});

//  购物车列表user_id
r.get("/v1/cartSearch/:user_id",(req,res)=>{
	var $user_id = req.params.user_id;

	sql = "select * from xz_shoppingcart_item where user_id=?"
	pool.query(sql,[$user_id],(err,result)=>{
		if(err) throw err;
		if(result.length>0){
			res.send(result);
		}else{
			res.send("0");
		}
	});
});

// 删除购物车
r.delete("/v1/cartDel/:iid",(req,res)=>{
	var $iid = req.params.iid;
	
	sql = "delete from xz_shoppingcart_item where iid=?"
	pool.query(sql,[$iid],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});

// 修改购物车条目中的购买数量
r.put("/v1/cartUpdatecount",(req,res)=>{
     var obj = req.body;
	console.log(req.body);
	sql = 'UPDATE xz_shoppingcart_item SET count=? WHERE iid = ?';
	pool.query(sql,[obj.count,obj.iid],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});

// 修改购物车条目中的是否勾选
r.put("/v1/cartUpdatechecked",(req,res)=>{
     var obj = req.body;
	console.log(req.body);
	sql = 'UPDATE xz_shoppingcart_item SET is_checked=? WHERE iid = ?';
	pool.query(sql,[obj.is_checked,obj.iid],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});









module.exports = r